package com.xingda.packing.dmss.task.handle;

import com.xingda.packing.dmss.domain.PackProductionLine;
import com.xingda.packing.dmss.domain.ProductBoxLocation;
import com.xingda.packing.dmss.enums.BoxLocationNo;
import com.xingda.packing.dmss.enums.TaskState;
import com.xingda.packing.dmss.enums.TaskType;
import com.xingda.packing.dmss.enums.WheelType;
import com.xingda.packing.dmss.task.ticket.PackingTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class PackingHandle implements TaskHandleService {
    @Override
    public boolean accept(PackProductionLine productionLine, int area) {
        return checkTask(productionLine.getRobot().getTaskTicket(area), TaskType.PACKING);
    }

    @Override
    public void process(PackProductionLine productionLine, int area) {
        PackingTicket ticket = (PackingTicket) productionLine.getRobot().getTaskTicket(area);
        for (ProductBoxLocation productBoxLocation : productionLine.getProductArea().getLocationList(area)) {
            if (productBoxLocation.getLocationNo() == ticket.getProductBoxLocationNo()) {
                if (!productBoxLocation.isPhotoFinish() || productBoxLocation.isPalletComing()) {
                    productionLine.getRobot().createAlarmEvent("任务进行中托盘已拿走,请人工处理当前未完成任务", area);
                    ticket.setState(TaskState.FINISH);
                    productionLine.setInitRunning(area, false);
                    productionLine.getRobot().setTaskTicket(ticket, area);
                    productionLine.getRobot().clear(area);
                    return;
                }
            }
        }
        if (productionLine.getRobot().canAssignTask(area)) {
            log.info("开始执行抓取位放装箱位-handle-区域{}", area);
            productionLine.getRobot().startGrab(WheelType.getByTypeName(ticket.getWheel().getVFree2()).getType(), ticket.getProductBoxLocationNo(), area);
            ticket.setState(TaskState.RUNING);
            // 事件记录
            productionLine.getRobot().handlePackingEvent(ticket, BoxLocationNo.getById(ticket.getProductBoxLocationNo()).getNo(), area);
            log.info("执行完成抓取位放装箱位-handle-区域{}", area);
        }
    }
}
